package com.njy.consumer.feign.aspect;


import cn.hutool.json.JSONUtil;
import com.njy.consumer.feign.annotation.SysLog;
import com.njy.pojo.LogInfo;
import com.njy.pojo.OperationType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.Duration;
import java.time.LocalDateTime;

@Component
@Aspect
public class SysLogAspect {

    @Pointcut("execution(* com.njy.consumer.feign.controller..*.*(..))")
    public void sysLogPoint(){ }


    @Around("sysLogPoint()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint){
        LogInfo logInfo = new LogInfo();
        MethodSignature methodSignature = (MethodSignature)proceedingJoinPoint.getSignature();
        Method method = methodSignature.getMethod();
        String methodName = method.getName();
        SysLog annotation = method.getAnnotation(SysLog.class);
        String description = annotation.description();
        OperationType operationType = annotation.operationType();
        String path = annotation.path();

        logInfo.setMethod(methodName);
        logInfo.setOperationType(operationType.getValue());
        logInfo.setPath(path);
        logInfo.setDescription(description);
        LocalDateTime startTime = LocalDateTime.now();
        logInfo.setCreationDate(startTime);
        Object response = null;
        try {
            logInfo.setReqParam(JSONUtil.toJsonStr(proceedingJoinPoint.getArgs()));
            //返回值
            response = proceedingJoinPoint.proceed();
            logInfo.setRespParam(JSONUtil.toJsonStr(response));

        } catch (Throwable throwable) {
            throwable.printStackTrace();
            logInfo.setRespParam(throwable.getMessage());
        }finally {
            LocalDateTime endTime = LocalDateTime.now();
            logInfo.setFinishDate(endTime);
            logInfo.setCost(String.valueOf(Duration.between(startTime, endTime).toMillis()));
            System.out.println(logInfo.toString());
        }
        return response;
    }
}
